<?php


namespace App\Libs\Common\Cache;


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class ConfigCacheClass
{
    protected static $seconds=3600;

    /**
     * Todo:: 响应数据
     * @param string $code
     * @param bool $status
     * @param string $message
     * @param array $data
     * @return array
     */
    protected static function responseArray($code='000000',$status=true,$message='Success',$data=[]){
        return array(
            'code' => $code,
            'status' => $status,
            'message' => $message,
            'data' => $data,
        );
    }

    /**
     * Todo:: 缓存全部 配置
     * @param int $type 1 重新缓存
     * @return \Illuminate\Support\Collection|mixed
     */
    public static function cacheConfigAll($type = 0){
        $cacheKey = "config:all";
        if ($type == 1) {
            // 重新缓存
            if (Cache::has($cacheKey)) {     //判断是否存在
                Cache::forget($cacheKey);      //删除缓存
            }
        }
        if(Cache::has($cacheKey)){
            $data = Cache::get($cacheKey);
        }else{
            $data = DB::table('config')->get();
            Cache::add($cacheKey, $data, self::$seconds);
        }
        return $data;
    }

    /**
     * Todo:: 缓存全部按照属性分类
     * @param int $type
     * @return mixed|object
     */
    public static function cacheConfigTypeArr($type = 0){
        $cacheKey = "config:typeArr";
        if ($type == 1) {
            // 重新缓存
            if (Cache::has($cacheKey)) {     //判断是否存在
                Cache::forget($cacheKey);      //删除缓存
            }
        }
        if(Cache::has($cacheKey)){
            $data = Cache::get($cacheKey);
        }else{
            $config = self::cacheConfigAll();
            $typeName = [];
            foreach($config as $key=>$val){
                $typeName[$val->type_name][$val->name] = $val;
            }
            $data = (object)$typeName;
            Cache::add($cacheKey, $data, self::$seconds);
        }
        return $data;
    }

    /**
     * Todo:: 清理配置缓存
     */
    public static function removeCacheConfigAll(){
        $configArray = array(
            "config:all",
            "config:typeArr",
        );
        foreach ($configArray as $key=>$val){
            if(Cache::has($val)){
                Cache::forget($val);
            }
        }
    }


    /**
     * Todo:: 缓存指定 类型配置
     * @param $typeName
     * @return \Illuminate\Support\Collection|mixed
     */
    public static function cacheConfigType($typeName){
        $cacheConfigTypeArr = self::cacheConfigTypeArr();
        if($cacheConfigTypeArr){
            if(isset($cacheConfigTypeArr->$typeName)){
                return $cacheConfigTypeArr->$typeName;
            }
        }
        return false;
    }

}
